package com.zsinfo.guoss.supplier.fragment;


import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.example.netcenter.NetCenter;
import com.example.netcenter.Event.Response;
import com.example.netcenter.RetrofitBuilder;
import com.example.netcenter.Url.ConstantsCode;
import com.example.netcenter.bean.ErrorBean;
import com.example.netcenter.bean.FruiteListBean;
import com.example.netcenter.bean.FruiteType;
import com.example.netcenter.bean.TipBean;
import com.example.utilcenter.event.MessageEvent;
import com.google.gson.Gson;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zsinfo.guoss.supplier.R;
import com.zsinfo.guoss.supplier.activity.FruitOfferAddActivity;
import com.zsinfo.guoss.supplier.activity.MarginActivity;
import com.zsinfo.guoss.supplier.activity.MarginToPayActivity;
import com.zsinfo.guoss.supplier.base.BaseFragment;
import com.zsinfo.guoss.supplier.customize.AlertDialog;
import com.zsinfo.guoss.supplier.utils.CommentUtil;
import com.zsinfo.guoss.supplier.utils.SharedPreferencesUtil;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * A simple {@link Fragment} subclass.
 */
public class OverseasFragment extends BaseFragment {


    @BindView(R.id.cacheRv)
    XRecyclerView cacheRv;
    @BindView(R.id.left_menu)
    RecyclerView left_menu;
    @BindView(R.id.fruit_top_text)
    TextView fruit_top_text;
    @BindView(R.id.fruit_top_jump)
    TextView fruit_top_jump;
    @BindView(R.id.jump_to_activity)
    LinearLayout jump_to_activity;
    private CommonAdapter<FruiteType.DataBean> leftMenuAdapter;

    private CommonAdapter<FruiteListBean.DataBean.ObjectsBean> rightMenuAdapter;


    private List<String> demoData;


    private NetCenter netCenter;

    private List<FruiteType.DataBean> fruitTypeData;

    private List<FruiteListBean.DataBean.ObjectsBean> fruitData;

    private int CurrentNo = 1;

    private int SelectPost = 0;

    private String TypeCode = "0";


    public OverseasFragment() {
        // Required empty public constructor
    }


    //左边一级菜单 2为海外水果
    private void initData() {


        netCenter.GetNetCenter(context, RetrofitBuilder.CreateApi().GOODS_TYPE_LIST(ConstantsCode.goods_type_list, SharedPreferencesUtil.getID(),
                "2",
                SharedPreferencesUtil.getWebsiteNode()),
                new Response() {
                    @Override
                    public void OK(Object data) {
                        FruiteType fruiteType = (FruiteType) data;
                        fruitTypeData.clear();
                        fruitTypeData.addAll(fruiteType.getData());
                        leftMenuAdapter.notifyDataSetChanged();
                        if (TypeCode.isEmpty() && fruiteType.getData().size() > 0) {

                            TypeCode = fruiteType.getData().get(0).getCode();
                            getFruiteList();


                        }
                    }

                    @Override
                    public void Fail(Throwable e) {

                    }

                    @Override
                    public void complete() {

                    }
                });
    }


    @BindView(R.id.data_less_layout)
    LinearLayout data_less_layout;

    //右边二级商品列表
    private void getFruiteList() {
        try {
            netCenter.GetNetCenter(context, RetrofitBuilder.CreateApi().GOODS_LIST(ConstantsCode.goods_list, SharedPreferencesUtil.getID(),
                    SharedPreferencesUtil.getWebsiteNode(),
                    TypeCode,
                    "2",
                    "15",
                    CurrentNo + ""),
                    new Response() {
                        @Override
                        public void OK(Object data) {

                            FruiteListBean fruiteListBean = (FruiteListBean) data;


                            if (fruiteListBean.getData().getObjects().size() <= 0) {
                                data_less_layout.setVisibility(View.VISIBLE);
                            } else {
                                data_less_layout.setVisibility(View.GONE);
                            }

                            if (CurrentNo == 1) {

                                fruitData.clear();
                            }

                            fruitData.addAll(fruiteListBean.getData().getObjects());

                            rightMenuAdapter.notifyDataSetChanged();


                        }

                        @Override
                        public void Fail(Throwable e) {

                            Log.e("Conker", "Fail: " + e);
                        }

                        @Override
                        public void complete() {
                            cacheRv.refreshComplete();
                            cacheRv.loadMoreComplete();
                        }
                    });
        } catch (Exception e) {
            Log.e("Conker", "Fail: " + e);
        }

    }


    @Override
    protected int getContentLayoutRes() {
        return R.layout.fragment_overseas;
    }


    @Override
    protected void initView(View view) {

        netCenter = new NetCenter();

        fruitTypeData = new ArrayList<>();

        fruitData = new ArrayList<>();

        fruit_top_jump.setText("进口类保证金");

        jump_to_activity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, MarginActivity.class);
                intent.putExtra("type", 2);
                startActivity(intent);
            }
        });

        initList();

        initData();

        EventBus.getDefault().register(this);

    }


    @Override
    public void onResume() {
        super.onResume();
        topTips();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    public void GetEvent(MessageEvent messageEvent) {

        topTips();

        initData();

        getFruiteList();

    }

    void topTips() {
        netCenter.GetNetCenter(RetrofitBuilder.CreateApi().margin_query(ConstantsCode.margin_query,
                SharedPreferencesUtil.getID(), "2"),
                new Response() {
                    @Override
                    public void OK(Object data) {

                        TipBean tipBean = (TipBean) data;

                        fruit_top_text.setText(tipBean.getData().getPrompt());

                    }

                    @Override
                    public void Fail(Throwable e) {

                    }

                    @Override
                    public void complete() {


                    }
                });
    }

    private void initList() {

        leftMenuAdapter = new CommonAdapter<FruiteType.DataBean>(context, R.layout.item_fruit_left_menu, fruitTypeData) {
            @Override
            protected void convert(final ViewHolder holder, final FruiteType.DataBean s, final int position) {


                //这个是recyclrview


                holder.setText(R.id.FruitName, s.getName());

                if (SelectPost == position) {

                    holder.itemView.setBackgroundColor(Color.WHITE);
                    holder.setVisible(R.id.left_sign, true);

                } else {

                    holder.itemView.setBackgroundColor(getResources().getColor(R.color.bg_gray));
                    holder.setVisible(R.id.left_sign, false);

                }


                if (s.getIsOfferToday() == 1) {
                    holder.setVisible(R.id.little_tips, true);
                } else {
                    holder.setVisible(R.id.little_tips, false);
                }


                holder.itemView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        v.setBackgroundColor(Color.WHITE);

                        holder.setVisible(R.id.left_sign, true);


                        CurrentNo = 1;

                        SelectPost = position;

                        TypeCode = s.getCode();

                        getFruiteList();

                        leftMenuAdapter.notifyDataSetChanged();

                    }
                });
            }
        };


        left_menu.setAdapter(leftMenuAdapter);

        left_menu.setLayoutManager(new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false));

        rightMenuAdapter = new CommonAdapter<FruiteListBean.DataBean.ObjectsBean>(getFragmentContext(), R.layout.item_fruit_right_menu, fruitData) {
            @Override
            protected void convert(ViewHolder holder, final FruiteListBean.DataBean.ObjectsBean s, int position) {


                //这个是Xrecyclrview

                holder.setText(R.id.f_name, s.getName()).setText(R.id.f_address, s.getSourceCity()).setText(R.id.fspecification, s.getSizeDesc()).setText(R.id.claim, s.getNorm());


                Button btn = holder.getView(R.id.btn_offer);
                GradientDrawable drawable = (GradientDrawable) btn.getBackground();
                drawable.setColor(getResources().getColor(R.color.main_color));
                btn.setEnabled(true);
                btn.setClickable(true);
                btn.setText("报价");
                if (s.getIsOfferToday() == 1) {
                    btn.setEnabled(false);
                    btn.setClickable(false);
                    drawable.setColor(getResources().getColor(R.color.gray));
                    btn.setText("已报价");
                }

                holder.setOnClickListener(R.id.btn_offer, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        QUOTED(s.getId());

                    }
                });
            }
        };


        cacheRv.setAdapter(rightMenuAdapter);

        cacheRv.setLayoutManager(new LinearLayoutManager(getFragmentContext(), LinearLayoutManager.VERTICAL, false));

        cacheRv.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                CurrentNo = 1;
                getFruiteList();

            }

            @Override
            public void onLoadMore() {
                CurrentNo++;
                getFruiteList();
            }
        });

    }


    private void QUOTED(final String GoodId) {
        netCenter.GetNetCenter(RetrofitBuilder.CreateApi().QUOTED(ConstantsCode.quoted,
                SharedPreferencesUtil.getID(),
                GoodId),
                new Response() {
                    @Override
                    public void OK(Object data) {


                        Intent intent = new Intent(context, FruitOfferAddActivity.class);
                        intent.putExtra("goodId", GoodId);
                        context.startActivity(intent);

                    }

                    @Override
                    public void Fail(Throwable e) {
                        try {
                            if (!e.getLocalizedMessage().contains("100000") && e.getLocalizedMessage().contains("Code")) {

                                ErrorBean errorBean = new Gson().fromJson(e.getMessage(), ErrorBean.class);

                                if (e.getLocalizedMessage().contains("100502")) {
                                    showToast(errorBean.getMsg());
                                } else if (e.getLocalizedMessage().contains("100503")) {

                                    new AlertDialog(context).builder()
                                            .setGone()

                                            .setMsg(errorBean.getMsg())
                                            .setPositiveButton("去缴纳", R.color.n_blue, new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {


                                                    Intent intent = new Intent(context, MarginActivity.class);
                                                    intent.putExtra("type", 2);
                                                    startActivity(intent);
                                                }
                                            })
                                            .setNegativeButton("再看看", R.color.black_font, new View.OnClickListener() {
                                                @Override
                                                public void onClick(View v) {

                                                }
                                            })

                                            .show();
                                }

                            }
                        } catch (Exception e1) {
                            e1.printStackTrace();


                        }
                    }

                    @Override
                    public void complete() {


                    }
                });
    }

}
